package Analizador;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

public class AnaLex extends javax.swing.JFrame {

    Lexico oAnaLex;
    ModeloDeTabla tsModelo = null;
    ModeloDeTabla modelo = null;

    public AnaLex() {
        oAnaLex = new Lexico();
        oAnaLex.TSInicia();
        tsModelo = new ModeloDeTabla(oAnaLex.TSTokens(), oAnaLex.TSLexemas(), oAnaLex.TSReservada());
        modelo = new ModeloDeTabla(oAnaLex.Tokens(), oAnaLex.Lexemas(), oAnaLex.Reservada());
        initComponents();
        cargarTablaSimbolos();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblTokenLexemas = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtaEntrada = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbTokenLexemas = new javax.swing.JTable();
        btnAnalizar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        lblEntrada = new javax.swing.JLabel();
        lblGrupo = new javax.swing.JLabel();
        lblArchivo = new javax.swing.JLabel();
        txtNombreArchivo = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtbTablaSimb = new javax.swing.JTable();
        lblTablaSimb = new javax.swing.JLabel();
        lblSalida = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jtaSalida = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Analizador Léxico Grupo 4");
        setPreferredSize(new java.awt.Dimension(1100, 700));

        lblTokenLexemas.setFont(new java.awt.Font("Comic Sans MS", 0, 14)); // NOI18N
        lblTokenLexemas.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTokenLexemas.setText("TOKENS Y LEXEMAS");

        jtaEntrada.setColumns(20);
        jtaEntrada.setRows(5);
        jScrollPane1.setViewportView(jtaEntrada);

        jtbTokenLexemas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "TOKEN", "LEXEMA", "SwPalRes"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jtbTokenLexemas);
        jtbTokenLexemas.getColumnModel().getColumn(2).setResizable(false);

        btnAnalizar.setText("ANALIZAR");
        btnAnalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnalizarActionPerformed(evt);
            }
        });

        btnLimpiar.setText("LIMPIAR");
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Comic Sans MS", 1, 24)); // NOI18N
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("ANALIZADOR LÉXICO (Grupo 4)");

        lblEntrada.setFont(new java.awt.Font("Comic Sans MS", 0, 14)); // NOI18N
        lblEntrada.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblEntrada.setText("CONTENIDO ARCHIVO DE ENTRADA");

        lblGrupo.setText("Presentado Por: Grupo 4 (Jenny Mayerly Diaz Diaz, Ricardo Gonzalez Salas Y Oscar Iván Rada Osorio)");

        lblArchivo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblArchivo.setText("Archivo Seleccionado:");

        txtNombreArchivo.setFocusable(false);

        btnBuscar.setText("BUSCAR ARCHIVO");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        jtbTablaSimb.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "TOKEN", "LEXEMA", "SwPalRes"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane3.setViewportView(jtbTablaSimb);

        lblTablaSimb.setFont(new java.awt.Font("Comic Sans MS", 0, 14)); // NOI18N
        lblTablaSimb.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTablaSimb.setText("TABLA DE SIMBOLOS");

        lblSalida.setFont(new java.awt.Font("Comic Sans MS", 0, 14)); // NOI18N
        lblSalida.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblSalida.setText("CONTENIDO ARCHIVO DE SALIDA");

        jtaSalida.setColumns(20);
        jtaSalida.setRows(5);
        jtaSalida.setFocusable(false);
        jScrollPane4.setViewportView(jtaSalida);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addComponent(lblTablaSimb, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtNombreArchivo)
                                .addGap(19, 19, 19))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblEntrada, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                                .addComponent(btnLimpiar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addGap(18, 18, 18)
                                                .addComponent(btnAnalizar, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addComponent(jScrollPane1))))
                                .addGap(10, 10, 10)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                                    .addComponent(lblTokenLexemas, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(8, 8, 8)
                                        .addComponent(lblSalida, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addContainerGap())))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblGrupo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblTokenLexemas, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblSalida, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblTablaSimb, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jScrollPane1)
                                .addGap(11, 11, 11)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(btnLimpiar)
                                    .addComponent(btnAnalizar))))))
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBuscar)
                    .addComponent(lblArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtNombreArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addComponent(lblGrupo)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAnalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnalizarActionPerformed
        oAnaLex.Inicia();
        oAnaLex.Analiza(jtaEntrada.getText());
        modelo = new ModeloDeTabla(oAnaLex.Tokens(), oAnaLex.Lexemas(), oAnaLex.Reservada());
        jtbTokenLexemas.setModel(modelo);

        BufferedReader salida;
        String cadena;
        try {
            salida = new BufferedReader(new FileReader("Salida.txt"));
            cadena = "";
            jtaSalida.setText("");
            while (salida.ready()) {
                cadena = salida.readLine();
                jtaSalida.append(cadena);
                jtaSalida.append(System.getProperty("line.separator"));
            }
            salida.close();
        } catch (IOException e) {
            System.out.println("Error:" + e.getMessage());
        }
    }//GEN-LAST:event_btnAnalizarActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        //Crear un nuevo filtro
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos de texto", "txt");
        //Se crea filechooser
        JFileChooser fileChooser = new JFileChooser();
        //se añade el filtro
        fileChooser.setFileFilter(filter);
        //titulo de ventana
        fileChooser.setDialogTitle("Seleccione archivo fuente...");
        //Se crea un nuevo File donde se especifica la ruta de destino
        File ruta = new File("C:");
        //Coloca la ruta donde se abrira el filechooser
        fileChooser.setCurrentDirectory(ruta);
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            txtNombreArchivo.setText(String.valueOf(file));
            Flujo s = new Flujo();
            s.Flujo(file);
            BufferedReader entrada;
            String cadena;
            try {
                entrada = new BufferedReader(new FileReader(file));
                cadena = "";
                jtaEntrada.setText("");
                while (entrada.ready()) {
                    cadena = entrada.readLine();
                    jtaEntrada.append(cadena);
                    jtaEntrada.append(System.getProperty("line.separator"));
                }
                entrada.close();
            } catch (IOException e) {
                System.out.println("Error:" + e.getMessage());
            }
        }
        JOptionPane.showMessageDialog(null, "¡Archivo cargado exitosamente!");
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        jtaEntrada.setText("");
        jtaSalida.setText("");
    }//GEN-LAST:event_btnLimpiarActionPerformed

    public void cargarTablaSimbolos() {
        File file = new File("TablaSimbolos.txt");
        Flujo s = new Flujo();
        s.Flujo(file);
        BufferedReader entrada;
        String cadena[];
        try {
            entrada = new BufferedReader(new FileReader(file));

            if (jtbTablaSimb != null) {
                jtbTablaSimb.removeAll();
            }
            while (entrada.ready()) {
                cadena = getRegistrarTablaSimbolos(entrada.readLine());
                oAnaLex.cargaObjTablaSimbolos(cadena);
            }
            tsModelo = new ModeloDeTabla(oAnaLex.TSTokens(), oAnaLex.TSLexemas(), oAnaLex.TSReservada());
            jtbTablaSimb.setModel(tsModelo);
            entrada.close();
        } catch (IOException e) {
            System.out.println("Error:" + e.getMessage());
        }
    }

    public String[] getRegistrarTablaSimbolos(String linea) {
        String register[];
        
        StringTokenizer splitter = new StringTokenizer(linea, ",,,");
        
        register = new String[splitter.countTokens()+1];
        if (splitter.countTokens() == 2) {
            for (int i = 0; i < register.length; i++) {
                if(i==1)
                    register[i] = ",";
                else
                    register[i] = splitter.nextToken();
            }
            return register;
        }

        splitter = new StringTokenizer(linea, ",");

        register = new String[splitter.countTokens()];
        for (int i = 0; i < register.length; i++) {
            register[i] = splitter.nextToken();
        }
        return register;
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new AnaLex().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnalizar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextArea jtaEntrada;
    private javax.swing.JTextArea jtaSalida;
    private javax.swing.JTable jtbTablaSimb;
    private javax.swing.JTable jtbTokenLexemas;
    private javax.swing.JLabel lblArchivo;
    private javax.swing.JLabel lblEntrada;
    private javax.swing.JLabel lblGrupo;
    private javax.swing.JLabel lblSalida;
    private javax.swing.JLabel lblTablaSimb;
    private javax.swing.JLabel lblTokenLexemas;
    private javax.swing.JTextField txtNombreArchivo;
    // End of variables declaration//GEN-END:variables
}
